package com.step.ems.pages.urgent

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.KeyboardArrowRight
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.rememberNestedScrollInteropConnection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.king.ultraswiperefresh.NestedScrollMode
import com.king.ultraswiperefresh.UltraSwipeRefresh
import com.king.ultraswiperefresh.indicator.classic.ClassicRefreshHeader
import com.step.ems.R
import com.step.ems.api.UrgentStatus
import com.step.ems.api.res.UrgentRes
import com.step.ems.common.RefreshType
import com.step.ems.common.UiState
import com.step.ems.component.EndlessLazyColumn
import com.step.ems.component.MyTopBar
import com.step.ems.component.PageStatus
import com.step.ems.ui.theme.ContentBg
import com.step.ems.ui.theme.DarkBlue
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun UrgentPageScreen(
    onItemClick: (UrgentRes) -> Unit,
    pages: Array<UrgentStatus> = UrgentStatus.entries.toTypedArray()
) {
    val viewModelMap: Map<Int, UrgentPageViewModel> = mapOf(
        0 to hiltViewModel<UrgentPageAlarmedViewModel>(),
        1 to hiltViewModel<UrgentPageAcceptViewModel>(),
        2 to hiltViewModel<UrgentPageArrowViewModel>(),
        3 to hiltViewModel<UrgentPageCompletedViewModel>(),
        4 to hiltViewModel<UrgentPageConfirmedViewModel>(),
    )

    val pagerState = rememberPagerState(pageCount = { pages.size })
    val coroutineScope = rememberCoroutineScope()

    LaunchedEffect(pagerState.currentPage) {
        viewModelMap[pagerState.currentPage]!!.initData()
    }

    Scaffold(topBar = {
        MyTopBar(stringResource(R.string.urgent))
    }) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .background(color = ContentBg)
        ) {
            Spacer(modifier = Modifier.height(1.dp))
            ScrollableTabRow(
                selectedTabIndex = pagerState.currentPage,
                edgePadding = 0.dp,
                divider = {},
                indicator = { tabPositions ->
                    Row(
                        modifier = Modifier.tabIndicatorOffset(tabPositions[pagerState.currentPage]),
                        horizontalArrangement = Arrangement.Center,
                    ) {
                        Box(
                            modifier = Modifier
                                .height(2.dp)
                                .width(20.dp)
                                .background(color = DarkBlue)
                        )
                    }
                }
            ) {
                pages.forEachIndexed { index, page ->
                    val title = stringResource(id = page.titleResId)
                    Tab(
                        selected = pagerState.currentPage == index,
                        onClick = { coroutineScope.launch { pagerState.animateScrollToPage(index) } },
                        text = { Text(text = title) },
                        unselectedContentColor = MaterialTheme.colorScheme.secondary
                    )
                }
            }
            Spacer(modifier = Modifier.height(12.dp))
            HorizontalPager(
                state = pagerState,
                verticalAlignment = Alignment.Top
            ) { index ->
                val viewModel = viewModelMap[index]!!
                val data by viewModel.data.collectAsStateWithLifecycle()
                val uiState by viewModel.uiState.collectAsStateWithLifecycle()
                PageStatus(uiState = uiState, total = data.size, retry = { viewModel.getData(RefreshType.Init) }) {
                    UrgentList(data = data, uiState = uiState, viewModel = viewModel, onItemClick = onItemClick)
                }
            }
        }
    }
}

@Composable
fun UrgentList(
    data: List<UrgentRes>,
    uiState: UiState,
    onItemClick: (UrgentRes) -> Unit,
    viewModel: UrgentPageViewModel,
) {
    val nestedScrollInteropConnection = rememberNestedScrollInteropConnection()
    val pullRefreshState = viewModel.pullRefreshState

    UltraSwipeRefresh(
        state = pullRefreshState,
        loadMoreEnabled = false,
        vibrateEnabled = true,
        onRefresh = {
            viewModel.getData(RefreshType.Pull)
        },
        onLoadMore = {},
        headerScrollMode = NestedScrollMode.Translate,
        headerIndicator = {
            ClassicRefreshHeader(it)
        },
    ) {
        EndlessLazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .nestedScroll(nestedScrollInteropConnection),
            uiState = uiState,
            items = data,
            itemKey = { item -> item.id },
            loadMore = { viewModel.getData(RefreshType.LoadMore) }
        ) { item ->
            UrgentItem(item, onItemClick)
            Spacer(modifier = Modifier.height(4.dp))
        }
    }
}

@Composable
fun UrgentItem(
    item: UrgentRes,
    onItemClick: (UrgentRes) -> Unit,
) {
    Column(
        modifier = Modifier
            .clickable { onItemClick(item) }
            .fillMaxWidth()
            .background(Color.White)
            .padding(horizontal = 16.dp, vertical = 12.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Text(
                text = stringResource(id = if (item.alarmType == 1) R.string.urgentTypePeople else R.string.urgentTypeStop),
                fontSize = 14.sp,
                color = Color.Black
            )
            Text(
                text = "2023-03-16 15:58:00",
                fontSize = 14.sp,
                color = Color.Gray,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        Spacer(modifier = Modifier.height(5.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            Image(
                painter = painterResource(id = if (item.alarmType == 1) R.drawable.urgent_trapped else R.drawable.urgent_failure),
                contentDescription = "alarmType",
                modifier = Modifier.size(48.dp),
                contentScale = ContentScale.Crop
            )
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = item.elevatorName,
                    fontSize = 16.sp,
                    color = Color.Black
                )
                Text(
                    text = item.address,
                    fontSize = 14.sp,
                    color = Color.Gray
                )
            }
            Icon(
                Icons.AutoMirrored.Rounded.KeyboardArrowRight,
                contentDescription = ">",
                tint = Color.LightGray
            )
        }
    }
}